package com.yisu.expressway.gas_station;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.location.LocationInfo;
import com.yisu.expressway.location.LocationListener;
import com.yisu.expressway.location.LocationService;
import com.yisu.expressway.model.GasStationObj;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.utils.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class NearByGasStationActivity extends BaseActivity implements PagingRecyclerView.SampleActionListener{

    @Bind(R.id.rv_gas_station_list)
    protected PagingRecyclerView mRv_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_by_gas_station);
        setTitle(R.string.nearby_gas_station);
//        mRv_list.addItemDecoration(new DividerListItemDecoration(this, LinearLayoutManager.VERTICAL,6,R.color.transparent));
//        mRv_list.init(this,200);//暂时没有分页故设置200
    }

    @Override
    public void fetchData(int start, int pageSize) {
        showLoading();
        LocationService.getInstance().start(new LocationListener() {
            @Override
            public void onSuccess(LocationInfo info) {
                getGasStationList(info);
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                dismissLoading();
                ToastUtil.displayShortToastMsg(NearByGasStationActivity.this,errorMessage);
            }
        });
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(this).inflate(R.layout.gas_station_list_item, parent, false);
        return new ViewHolder(mView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {

        final ViewHolder holder = (ViewHolder)_holder;
        final GasStationObj item = (GasStationObj)_item;

        if(item != null){
            holder.mTv_address.setText(item.address);
            holder.mTv_distance.setText(item.distance + "公里");
            holder.mTv_name.setText(item.stationName);
            holder.mTv_phoneNumber.setText(item.contactPhone);

            holder.mBtn_navi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doNavi(item);
                }
            });
        }
    }

    class ViewHolder extends BaseRvAdapter.SampleViewHolder{

        @Bind(R.id.tv_station_name)
        TextView mTv_name;
        @Bind(R.id.tv_station_address)
        TextView mTv_address;
        @Bind(R.id.tv_distance)
        TextView mTv_distance;
        @Bind(R.id.tv_contact_number)
        TextView mTv_phoneNumber;
        @Bind(R.id.ibtn_navi)
        ImageButton mBtn_navi;

        public ViewHolder(View view){
            super(view);
            ButterKnife.bind(this,view);

        }
    }

    /**
     * 获取附近加油站列表
     * @param info
     */
    private void getGasStationList(LocationInfo info){
        Map<String, Object> params = new HashMap();
        params.put("longitude", info.getLongitude());
        params.put("latitude", info.getLatitude());
        ApiClientHelper.postApi(ApiSetting.getNearByGasStation(), new TypeToken<ArrayList<GasStationObj>>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<ArrayList<GasStationObj>>>() {
            @Override
            public void onResponse(ApiResult<ArrayList<GasStationObj>> result) {
                dismissLoading();

                if (!result.success) {
                    ToastUtil.displayLongToastMsg(NearByGasStationActivity.this, result.getMsg());
                    return;
                }

                ArrayList<GasStationObj> mList = result.getResult();
                mRv_list.dataFetchDone(mList);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissLoading();
                ToastUtil.displayShortToastMsg(NearByGasStationActivity.this, volleyError.getMessage());
            }
        }, this);
    }

    private void doNavi(GasStationObj item){
        LocationInfo mStartLocInfo = LocationService.getInstance().getLocationResult();
        double mLatStart = mStartLocInfo.getLatitude();
        double mLonStart = mStartLocInfo.getLongitude();

        double mLatEnd = item.latitude;
        double mLonEnd = item.longitude;

        LatLng pt_start = new LatLng(mLatStart, mLonStart);
        LatLng pt_end = new LatLng(mLatEnd, mLonEnd);

        NaviParaOption para = new NaviParaOption()
                .startPoint(pt_start).endPoint(pt_end);

        try {
            BaiduMapNavigation.setSupportWebNavi(true);
            BaiduMapNavigation.openBaiduMapNavi(para, this);
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            ToastUtil.displayShortToastMsg(this,e.toString());
        }

        BaiduMapRoutePlan.finish(this);
    }
}
